package lumis.service.seo.sitemap;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.transaction.ITransaction;
import lumis.portal.transaction.PortalTransactionFactory;

/**
 * Serves the sitemap xml content.
 * <p> 
 * This servlet expects that the URL ends with the sitemap filename. 
 * The sitemap service instance to be used is resolved from the sitemap filename. The
 * service instance configured to serve that filename is used. If none is available, a 
 * not found (404) response is sent.
 * 
 * @version $Revision: 10825 $ $Date: 2009-08-04 12:36:40 -0300 (Tue, 04 Aug 2009) $
 * @since 5.0.0
 */
@SuppressWarnings("serial")
public class SitemapServlet extends HttpServlet
{
	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		try
		{
			ITransaction transaction = PortalTransactionFactory.createTransaction();
            try
            {
            	transaction.begin();
            	
            	String url = req.getRequestURL().toString();
            	//get the sitemap file name
            	String name = url.subSequence(url.lastIndexOf("/") + 1, url.lastIndexOf(".xml")).toString();
            	//     baseurl =    http            ://    localhost:8080/portal/
            	String baseUrl = url.substring(0, url.lastIndexOf(req.getServletPath() + "/")) + "/";

            	SessionConfig sessionConfig = SessionConfig.getCurrentSessionConfig();
            	
        		String sitemapList = null;
        		
        		// for each sitemap service instance
        		Collection<String> serviceInstanceIds = ManagerFactory.getServiceInstanceManager().getIdsByServiceId(sessionConfig, 
            			"lumis.service.seo.sitemap", transaction);
            	for (String serviceInstanceId: serviceInstanceIds)
            	{
            		//get the Sitemap archive name from custom properties
            		String sitemap = ManagerFactory.getServiceInstanceManager()
            				.getCustomProperty(sessionConfig, serviceInstanceId, "sitemaps", transaction);

            		//compare the archive name with the requested one
            		if (name.equals(sitemap))
            		{
            			List<String> channelIds = ManagerFactory.getEntityManager().createQuery(
            	        		"select s.channelId from SitemapChannel s, ContentVersion cv " +
            	        		"where s.id = cv.itemId and cv.contentLocale.content.serviceInstanceId = :si")
            	        		.setParameter("si", serviceInstanceId)
            	        		.getResultList();
            			sitemapList = SitemapGenerator.createSitemap(sessionConfig, channelIds, baseUrl, transaction);
            			break;
            		}
            	}
            	if(sitemapList != null)
            	{	
            		resp.setContentType("text/xml");
            		resp.setCharacterEncoding("UTF-8");
            		PrintWriter p = resp.getWriter();
            		p.println(sitemapList);
            	}
            	else
            	{
            		resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            	}
            	transaction.commit();
            }
			finally
			{
				transaction.dispose();
			}
		}
		catch (PortalException e)
		{
			throw new ServletException(e.getMessage(), e);
		}
	}
}
